package org.blackcat.core.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.blackcat.core.annotation.IsNull;
import org.blackcat.core.annotation.Length;
import org.blackcat.core.annotation.Size;
import org.blackcat.domain.common.MsgResponse;
import org.blackcat.domain.enums.ResponseCodeEnum;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * Created by Duo Duo on 2017/1/9.
 */
@Component
@Aspect
public class FieldAdvice implements Ordered {

    @Pointcut("@annotation(org.blackcat.core.annotation.Validation)")
    public void validationAdvice(){}


    @Around("validationAdvice()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
        Object obj = null;
        Object[] args = pjp.getArgs();
        if(args != null && args.length != 0){
            Object arg = args[0];
            //只有一个参数并且是String类型的判断
            if(arg == null || arg.equals("null") || arg.equals("")){
                return new MsgResponse<>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR,"参数不能为空！");
            }
            Field[] fields = arg.getClass().getDeclaredFields();
            obj = fieldValidation(fields,arg);
            if(obj != null){
                return obj;
            }
        }
        obj = pjp.proceed();
        return obj;
    }
    /**
     * 参数验证
     * @param fields
     * @param arg
     * @return
     * @throws IllegalAccessException
     */
    private Object fieldValidation(Field[] fields,Object arg) throws IllegalAccessException {
        for(Field field:fields){
            if(field.getType().isMemberClass()){
                Object innerObj = field.get(arg);
                Field[] innerFields = field.getType().getDeclaredFields();
                fieldValidation(innerFields,innerObj);
            }
            if(AnnotationSolve.isNull(field,arg)){
                return new MsgResponse<Object>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR,field.getAnnotation(IsNull.class).value());
            }else if(AnnotationSolve.notLength(field,arg)){
                return new MsgResponse<Object>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR,field.getAnnotation(Length.class).value());
            }else if(AnnotationSolve.notSize(field,arg)){
                return new MsgResponse<Object>(ResponseCodeEnum.REQUEST_PARAMETER_ERROR,field.getAnnotation(Size.class).value());
            }
        }
        return null;
    }
    /**
     * 先执行此aop再执行事务aop，否则不能成功！
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
